# -*- coding: utf-8 -*-

class AssemblyOrderController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:getAssemblyOrderProductsById]


  #显示新增组合订单页面
  def newAssembly
    
  end

  #显示编辑组合订单页面
  def editAssembly
    
  end
  
  #显示组合列表页面
  def assemblyOrderList

  end

  #显示组合审批列表页面
  def assemblyOrderAuditList

  end

  #显示审批组合订单页面
  def auditAssemblyOrder

  end
  
  def getAllAssemblyOrders
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehouse_id = :warehouse_id'
      else
        conditionsStr = conditionsStr+' AND warehouse_id = :warehouse_id'
      end
      conditionsHash[:warehouse_id] = params[:warehouse_id].to_i
    end

    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'assembly_order_products.product_id = :product_id'
      else
        conditionsStr = conditionsStr+' AND assembly_order_products.product_id = :product_id'
      end
      conditionsHash[:product_id] = params[:product_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'assembly_orders.action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND assembly_orders.action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'assembly_orders.action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND assembly_orders.action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if params[:auditing_status].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'auditing_status like :auditing_status'
      else
        conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
      end
      conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
    end
    
    count = AssemblyOrder.countAllAssemblyOrders conditionsStr, conditionsHash
    assemblyOrders = AssemblyOrder.findAllAssemblyOrders conditionsStr,conditionsHash,paramsHash
    
    jsonStr="{totalProperty:"+count.to_s+",root:"+assemblyOrders.to_json(:include=>[:employee,:department,:auditor,:warehouse,:product])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #组合，只有在审批通过后，数据才正式进入结算表。
  def create
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    assemblyOrder = AssemblyOrder.new
    assemblyOrder.company_id = session[:company_id]
    assemblyOrder.department_id = session[:department_id]
    assemblyOrder.employee_id = session[:employee_id]
    assemblyOrder.warehouse_id = paramsHash["warehouse_id"]
    assemblyOrder.description = paramsHash["description"]

    #批处理多个product
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #如果不为空则加入
      if productHash["product_id"] !=""
        assemblyOrderProduct = AssemblyOrderProduct.new
        assemblyOrderProduct.product_id = productHash["product_id"]
        assemblyOrderProduct.quantity = productHash["quantity"].to_i
        assemblyOrderProduct.description = productHash["description"]
        assemblyOrder.assembly_order_products << assemblyOrderProduct
        #把每一个产品的组成进行一一记录
        subProducts = ProductsComponent.where("product_id = ?",productHash["product_id"].to_i)
        subProducts.each do |product|
          assemblyOrderDetail = AssemblyOrderDetail.new
          assemblyOrderDetail.product_id = product.component_id
          #乘以assemblyOrder.quantity
          assemblyOrderDetail.quantity = product.quantity * productHash["quantity"].to_i
          assemblyOrder.assembly_order_details << assemblyOrderDetail
          assemblyOrderProduct.assembly_order_details << assemblyOrderDetail #和上面的语句一起，起到加上关联的作用
        end
      end
    end
    
    #assemblyOrder.quantity = params[:quantity]
    #assemblyOrder.product_id = productId

    assemblyOrder.action_date = Time.new.strftime("%Y-%m-%d")

    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash["temporary"] == '1' || paramsHash["temporary"] == 1
      assemblyOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_assembly_add == "否"
        assemblyOrder.auditing_status = Constants::PASS_APPLY_ADD
        assemblyOrder.deal_with_status = ''
      else
        assemblyOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end
    
    #assemblyOrder.save!

    #开始事务，确保在流水号正常的情况下，保存入库订单时,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],AssemblyOrder.name).first

        sequence.seq_no = sequence.seq_no + 1
        assemblyOrder.seq_number = sequence.seq_no
        assemblyOrder.order_number = sequence.ab + ":" + assemblyOrder.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        assemblyOrder.save!

        #如果组合订单的新增不需要审批，直接入汇总表
        if paramsHash["temporary"] != '1' && sysParam.audit_for_assembly_add == "否"
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。

          productsHashArray.each do |productHash|
            productCollection = ProductCollection.new
            productCollection.company_id = assemblyOrder.company_id
            productCollection.department_id = assemblyOrder.department_id
            productCollection.employee_id = assemblyOrder.employee_id
            productCollection.warehouse_id = assemblyOrder.warehouse_id
            productCollection.action_date = assemblyOrder.action_date

            productCollection.product_id = productHash["product_id"]
            productCollection.quantity = productHash["quantity"]
            productCollection.description =  productHash["description"]
            productCollection.resource_id =  assemblyOrder.id
            productCollection.resource_type =  AssemblyOrder.name
            productCollection.save!
          end
          #以上是减去一个产品，以下是增加拆分后的产品。
          assemblyOrderDetails = assemblyOrder.assembly_order_details.where("assembly_order_product_id = #{assemblyOrderProduct.id}")
          assemblyOrderDetails.each do |assemblyOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = assemblyOrder.company_id
            productCollection.department_id = assemblyOrder.department_id
            productCollection.employee_id = assemblyOrder.employee_id
            productCollection.warehouse_id = assemblyOrder.warehouse_id
            productCollection.product_id = assemblyOrderDetail.product_id
            productCollection.quantity = 0 - assemblyOrderDetail.quantity
            productCollection.description =  assemblyOrder.description
            productCollection.action_date = assemblyOrder.action_date
            productCollection.resource_id =  assemblyOrder.id
            productCollection.resource_type =  AssemblyOrder.name
            productCollection.save!
          end
        end
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end


  #编辑拆分记录，但在审批时才正式拆分数据到结算表
  def update
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    
    assemblyOrder = AssemblyOrder.find(paramsHash["id"])
    assemblyOrder.company_id = session[:company_id]
    assemblyOrder.department_id = session[:department_id]
    assemblyOrder.employee_id = session[:employee_id]
    assemblyOrder.warehouse_id = paramsHash["warehouse_id"]
    assemblyOrder.description = paramsHash["description"]

    assemblyOrder.action_date = Time.new.strftime("%Y-%m-%d")

    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash["temporary"]  == '1'
      assemblyOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_assembly_add == "否"
        assemblyOrder.auditing_status = Constants::PASS_APPLY_ADD
      else
        assemblyOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
      assemblyOrder.deal_with_status = ''
    end

    begin
      AssemblyOrderProduct.transaction do
     
        #批处理多个product
        productsHashArray = paramsHash["products"]
        #先清了所有的数组内容。这样再添加新的，没有被添加的自然会求出差，提交时，自然删除掉。
        assemblyOrder.assembly_order_products.clear

        #把产品细节也从新删除一次。即从新编辑时，把以前的记录清掉，从新添加，插入。
        assemblyOrder.assembly_order_details.clear
        
        productsHashArray.each do |productHash|
          #如果不为空则加入
          if productHash["product_id"] !=""
            assemblyOrderProduct = AssemblyOrderProduct.new
            assemblyOrderProduct.product_id = productHash["product_id"]
            assemblyOrderProduct.quantity = productHash["quantity"].to_i
            assemblyOrderProduct.description = productHash["description"]
            assemblyOrder.assembly_order_products << assemblyOrderProduct
            #把每一个产品的组成进行一一记录
            subProducts = ProductsComponent.where("product_id = ?",productHash["product_id"].to_i)
            subProducts.each do |product|
              assemblyOrderDetail = AssemblyOrderDetail.new
              assemblyOrderDetail.product_id = product.component_id
              #乘以assemblyOrder.quantity
              assemblyOrderDetail.quantity = product.quantity * productHash["quantity"].to_i
              assemblyOrder.assembly_order_details << assemblyOrderDetail
              assemblyOrderProduct.assembly_order_details << assemblyOrderDetail #和上面的语句一起，起到加上关联的作用
            end
          end
        end
        assemblyOrder.save!

        #如果组合订单的新增不需要审批，直接入汇总表
        if paramsHash["temporary"] != '1' && sysParam.audit_for_assembly_add == "否"
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'AssemblyOrder' AND resource_id = #{assemblyOrder.id}")
        
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          productCollection = ProductCollection.new
          productCollection.company_id = assemblyOrder.company_id
          productCollection.department_id = assemblyOrder.department_id
          productCollection.employee_id = assemblyOrder.employee_id
          productCollection.warehouse_id = assemblyOrder.warehouse_id
          productCollection.action_date = assemblyOrder.action_date

          productCollection.product_id = assemblyOrder.product_id
          productCollection.quantity = assemblyOrder.quantity
          productCollection.description =  assemblyOrder.description
          productCollection.resource_id =  assemblyOrder.id
          productCollection.resource_type =  AssemblyOrder.name
          productCollection.save!
          #以上是减去一个产品，以下是增加拆分后的产品。
          assemblyOrderDetails = assemblyOrder.assembly_order_details.where("assembly_order_product_id = #{assemblyOrderProduct.id}")
          assemblyOrderDetails.each do |assemblyOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = assemblyOrder.company_id
            productCollection.department_id = assemblyOrder.department_id
            productCollection.employee_id = assemblyOrder.employee_id
            productCollection.warehouse_id = assemblyOrder.warehouse_id
            productCollection.product_id = assemblyOrderDetail.product_id
            productCollection.quantity = 0 - assemblyOrderDetail.quantity
            productCollection.description =  assemblyOrder.description
            productCollection.action_date = assemblyOrder.action_date
            productCollection.resource_id =  assemblyOrder.id
            productCollection.resource_type =  AssemblyOrder.name
            productCollection.save!
          end
        end
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到某一个组合订单的组合成的产品明细
  def getAssemblyOrderProductsById
    assemblyOrderProducts =  AssemblyOrderProduct.where(assembly_order_id:params[:assembly_order_id])
    jsonStr="{totalProperty:"+assemblyOrderProducts.length.to_s+",root:"+assemblyOrderProducts.to_json(:include=>[:product])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  #现在的ID已经不是assemblyOrderId,已经是assemblyOrderProductId
  def getAssemblyOrderDetailsById
    assemblyOrderDetails =  AssemblyOrderDetail.where(assembly_order_product_id:params[:assembly_order_product_id])
    jsonStr="{totalProperty:"+assemblyOrderDetails.length.to_s+",root:"+assemblyOrderDetails.to_json(:include=>[:product])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getAllAssemblyOrdersByAuditStatus

    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:warehouse_id].to_s != ''
      conditionsStr = conditionsStr + ' AND warehouse_id = :warehouse_id'
      conditionsHash[:warehouse_id] = params[:warehouse_id].to_i
    end

    if params[:product_name].to_s != ''
      conditionsStr = conditionsStr+' AND products.product_id = :product_id'
      conditionsHash[:product_id] = params[:product_id].to_i
    end

    if params[:begin_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      conditionsStr = conditionsStr+' AND action_date <= :end_date'
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = AssemblyOrder.countAllAssemblyOrders conditionsStr, conditionsHash
    assemblyOrders = AssemblyOrder.findAllAssemblyOrders conditionsStr,conditionsHash,paramsHash
    jsonStr="{totalProperty:"+count.to_s+",root:"+assemblyOrders.to_json(:include=>[:employee,:department,:auditor,:product,:warehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #审批组合产品，并添加到结算表中。
  def updateAuditingStatus
    assemblyOrder = AssemblyOrder.find(params[:assembly_order_id])
    info = nil
    if assemblyOrder !=nil
      auditingStatus = params[:auditing_status]
      assemblyOrder.auditor_id = session[:employee_id]
      assemblyOrder.audit_opinion =  params[:audit_opinion]
      AssemblyOrder.transaction do
        if(auditingStatus == "是")
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'AssemblyOrder' AND resource_id = #{params[:assembly_order_id]}")
          
          auditingStatus = Constants::PASS_APPLY_ADD
          assemblyOrder.auditing_status = auditingStatus
          assemblyOrder.action_date = Time.new.strftime("%Y-%m-%d")
          assemblyOrder.save!
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          assemblyOrderProducts = assemblyOrder.assembly_order_products
          assemblyOrderProducts.each do |assemblyOrderProduct|
            productCollection = ProductCollection.new
            productCollection.company_id = assemblyOrder.company_id
            productCollection.department_id = assemblyOrder.department_id
            productCollection.employee_id = assemblyOrder.employee_id
            productCollection.warehouse_id = assemblyOrder.warehouse_id
            productCollection.action_date = assemblyOrder.action_date

            productCollection.product_id = assemblyOrderProduct.product_id
            productCollection.quantity = assemblyOrderProduct.quantity
            productCollection.description =  assemblyOrder.description
            productCollection.resource_id =  assemblyOrder.id
            productCollection.resource_type =  AssemblyOrder.name
            productCollection.save!
            #以上是减去一个产品，以下是增加拆分后的产品。
            assemblyOrderDetails = assemblyOrder.assembly_order_details.where("assembly_order_product_id = #{assemblyOrderProduct.id}")
            assemblyOrderDetails.each do |assemblyOrderDetail|
              productCollection = ProductCollection.new
              productCollection.company_id = assemblyOrder.company_id
              productCollection.department_id = assemblyOrder.department_id
              productCollection.employee_id = assemblyOrder.employee_id
              productCollection.warehouse_id = assemblyOrder.warehouse_id
              productCollection.product_id = assemblyOrderDetail.product_id
              productCollection.quantity = 0 - assemblyOrderDetail.quantity
              productCollection.description =  assemblyOrder.description
              productCollection.action_date = assemblyOrder.action_date
              productCollection.resource_id =  assemblyOrder.id
              productCollection.resource_type =  AssemblyOrder.name
              productCollection.save!
            end
          end
          
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
          assemblyOrder.auditing_status = auditingStatus
          assemblyOrder.save!
        end
      end
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据某Id得到拆分记录的信息。
  def getAssemblyOrderById
    begin
      assemblyOrder = AssemblyOrder.find(params[:id],:include=>[:product])
      rootStr = assemblyOrder.to_json(:include=>[:product])
      jsonStr = "{root:["+rootStr+"]}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #申请撤消
  def applyToCancel
    begin
      assemblyOrder = AssemblyOrder.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_assembly_cancel == "否"
        assemblyOrder.auditing_status = Constants::PASS_APPLY_CANCEL
        assemblyOrder.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'AssemblyOrder' AND resource_id = #{params[:id]}")
        #如果不需要审批，则把汇总表中的数据设置为is_locked = 1
      else
        assemblyOrder.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      assemblyOrder.auditor_id = session[:employee_id]
      assemblyOrder.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
